package cn.tedu.sp06.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
@Component
public class AccessFilter extends ZuulFilter {

//    设置过滤器类型 : pre routing  post  error
    @Override
    public String filterType() {
//        return "pre"
        return FilterConstants.PRE_TYPE;
    }
//    过滤器位置序号
    @Override
    public int filterOrder() {
        return 6;
    }
//     判断针对当前请求,是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*
        * 调用商品判断权限
        * 调用用户和订单,不检查权限
        * */
//        调用的服务id
        RequestContext  ctx=  RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equals(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
//        http://localhost:3001/item-service/t34t34?token=t34t34
//        获得requst对象
        RequestContext ctx =  RequestContext.getCurrentContext();
        HttpServletRequest request =ctx.getRequest();
//        接收token参数
       String token = request.getParameter("token");
//        如果没token 阻止访问,直接返回响应
        if (StringUtils.isBlank(token)){
//            阻止继续访问
            ctx.setSendZuulResponse(false);
//            直接返回响应
            ctx.addZuulResponseHeader("Content-Type","Text/html;charset=UTF-8" );
            ctx.setResponseBody("Not Login!! 未登录!!");
        }
//        这个返回值返回任何数据都行  暂时不起作用
        return null;
    }
}
